package com.controller;

import com.beans.CommentEntity;
import com.beans.DeviceEntity;
import com.beans.ErrorStatusEnum;
import com.common.entity.R;
import com.repository.CommentRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 设备留言接口
 *
 * @author gm
 * @date 2020/6/3
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("comment")
public class CommentController {

    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private CommentRepository commentRepository;

    /**
     * 获取所有设备留言
     *
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/31
     */
    @GetMapping("getComment")
    public R getComment() {
        List<CommentEntity> resultList = commentRepository.findAll();
        Object total = entityManager.createNativeQuery("select count(id) from comment").getSingleResult();
        R ok = R.ok();
        ok.put("rows", resultList);
        ok.put("total", total);
        return ok;
    }

    /**
     * 分页获取设备留言，可根据需求传入不同数量的参数
     *
     * @param deviceId 设备ia
     * @param state 状态(0.审核失败 1.审核中 2.审核通过)
     * @param page  第几页
     * @param rows  每页几条数据
     * @param sort  排序字段名
     * @param order 排序方式  asc desc
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/5
     */
    @GetMapping("getCommentForPage")
    public R getCommentForPage(Integer deviceId, Integer state, Integer page, Integer rows, String sort, String order) {
        //region 组装hql
        StringBuilder sql = new StringBuilder("select * from comment where 1 = 1 ");
        StringBuilder countSql = new StringBuilder("select count(id) from comment where 1 = 1 ");
        if (deviceId != null) {
            sql.append(" and deviceId = :deviceId ");
            countSql.append(" and deviceId = :deviceId ");
        }
        if (state != null) {
            sql.append(" and state = :state ");
            countSql.append(" and state = :state ");
        }
        if (!StringUtils.isEmpty(sort)) {
            sql.append(" order by ").append(sort).append(" ");
            if (!StringUtils.isEmpty(order)) {
                sql.append(order);
            }
        }
        if (page != null && rows != null) {
            sql.append(" limit :offset , :rows ");
        }
        //endregion 组装hql
        //region 组装查询对象和参数
        Query query = entityManager.createNativeQuery(sql.toString(), CommentEntity.class);
        Query queryCount = entityManager.createNativeQuery(countSql.toString());
        if (deviceId != null) {
            query.setParameter("deviceId", deviceId);
            queryCount.setParameter("deviceId", deviceId);
        }
        if (state != null) {
            query.setParameter("state", state);
            queryCount.setParameter("state", state);
        }
        if (page != null && rows != null) {
            query.setParameter("offset", (page - 1) * rows).setParameter("rows", rows);
        }
        List<DeviceEntity> resultList = query.getResultList();
        Object count = queryCount.getSingleResult();
        R ok = R.ok();
        ok.put("total", count);
        ok.put("rows", resultList);
        return ok;
    }

    /**
     * 新增设备留言
     *
     * @param comment
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @PostMapping("saveComment")
    public R saveComment(@RequestBody @Valid CommentEntity comment) {
        comment.setTime(new Date());
        comment.setState(1);
        comment = entityManager.merge(comment);
        return R.ok(comment);
    }

    /**
     * 审核设备留言
     *
     * @param id    留言id
     * @param state 审核状态（0.删除留言 2.通过留言）
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/2
     */
    @PostMapping("updateComment")
    public R updateComment(Integer id, Integer state) {

        int i = entityManager.createQuery("update CommentEntity set state = :state, passTime = :time where id = :id and state = 1").setParameter("state", state).setParameter("time", new Date()).setParameter("id", id).executeUpdate();
        if (i == 0) {
            return R.error(ErrorStatusEnum.PARAMS_ILLEGAL.code(), "留言不存在或已被审核，删除失败！");
        }
        return R.ok();
    }

}
